const vscode = require('vscode');
const { globalStateKey, getDefaultTreeData } = require('./config.js');

class JsonTreeDataProvider {
    constructor(context) {
        this.filterText = '';
        this.context = context;
        this._onDidChangeTreeData = new vscode.EventEmitter();
        this.onDidChangeTreeData = this._onDidChangeTreeData.event;
        this.loadData();
    }

    // 获取存储数据
    getStorageData() {
        const data = this.context.globalState.get(globalStateKey) || getDefaultTreeData()
        return JSON.parse(JSON.stringify(data))
    }

    // 加载数据
    loadData() {
        // 读取缓存数据
        this.data = this.getStorageData()
    }

    // 更新存储数据
    updateData(data) {
        try {
            this.context.globalState.update(globalStateKey, data);
            this.refresh();
        } catch (err) {
            vscode.window.showErrorMessage(`数据更新失败: ${err.message}`);
        }
    }

    // 重置数据
    resetData() {
        this.filterText = ''
        this.refresh()
    }

    // 刷新数据
    refresh() {
        if (this.filterText) {
            this.filter(this.filterText)
        } else {
            this.loadData();
            this._onDidChangeTreeData.fire();
        }
    }

    // 过滤数据
    filter(filterText) {
        this.filterText = filterText
        const _filterText = filterText.toLowerCase()
        this.loadData()
        this.data.forEach(e => {
            e.children = e.children.filter(_e => {
                const _name = _e.name.toLowerCase()
                const _content = _e.content.toLowerCase()
                return _name.includes(_filterText) || _content.includes(_filterText)
            })
        })

        this._onDidChangeTreeData.fire()
    }

    // 返回子节点
    getChildren(element) {
        if (!element) {
            return this.data; // 返回根节点
        }
        return element.children || [];
    }

    // 返回 TreeItem
    getTreeItem(element) {
        const isItem = !element.children; // 判断是否为item节点
        const item = new vscode.TreeItem(
            element.name,
            isItem ?
                vscode.TreeItemCollapsibleState.None :	 // 无子节点则不可折叠
                vscode.TreeItemCollapsibleState.Expanded // 有子节点则展开
        );

        if (isItem) {
            // 设置悬停提示
            item.tooltip = new vscode.MarkdownString(`**${element.content}**`);

            // 点击节点时粘贴代码
            item.command = {
                command: 'extension.pasteSnippet',
                title: '粘贴代码',
                arguments: [element.content]
            };
        }

        // 设置上下文值（用于菜单条件判断）
        if (isItem) {
            item.contextValue = "item"; // item节点类型菜单
            item.iconPath = new vscode.ThemeIcon('file');
        } else {
            item.contextValue = "tag"; // tag节点类型菜单
            item.iconPath = new vscode.ThemeIcon('tag');
        }

        return item;
    }
}

module.exports = {
    JsonTreeDataProvider
}